//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.hustcad.plm.pdm.flowexpansion.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.entity.BaseObject;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.pdm.audit.util.TyplmAuditLogUtil;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import com.hustcad.plm.pdm.ec.controller.TyplmChangeController;
import com.hustcad.plm.pdm.flowexpansion.model.dto.TypesAndLifekeysDto;
import com.hustcad.plm.pdm.flowexpansion.model.entity.TypeWorkFlowRule;
import com.hustcad.plm.pdm.flowexpansion.model.vo.LifekeysVo;
import com.hustcad.plm.pdm.flowexpansion.service.TyplmWorkFlowRuleService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlow;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowQueryDTO;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowService;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.audit.AuditLogDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.utils.ArgumentUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsyxdl.emuns.MyCollectErrorCodeEnum;

@RestController
@Api(
        tags = {"流程模板规则控制层"}
)
@RequestMapping({"/rest/v1/workflowRule"})
public class TyplmWorkFlowRuleController {

    private static final Logger log = LoggerFactory.getLogger(TyplmWorkFlowRuleController.class);

    @Resource
    private TyplmWorkFlowRuleService typlmWorkFlowRuleService;
    @Resource
    private TyplmWorkFlowService typlmWorkFlowService;

    @Resource
    TyplmPartService typlmPartService;
    @Resource
    private TyplmDocumentService typlmDocumentService;

    private static final String OID = "oid";
    private static final String TYPE_OID = "typeoid";
    private static final String TYPE_OTYPE = "typeotype";
    private static final String WORK_FLOW_OID = "workFlowOid";
    private static final String WORK_FLOW_OTYPE = "workFlowOtype";
    private static final String LIFE_CYCLE_STAGE_KEYS = "lifeCycleStageKeys";
    private static final String DISABLED = "disabled";

    public TyplmWorkFlowRuleController() {
    }

    @PostMapping({"/createTypeWorkflowRule"})
    @ApiOperation(
            value = "创建流程模板规则",
            notes = "创建流程模板规则",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult createTypeWorkflowRule(@RequestBody TypeWorkFlowRule typeWorkFlowRule) {
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getTypeoid(), "typeoid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getTypeotype(), "typeotype");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getLifeCycleStageKeys(), "lifeCycleStageKeys");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getWorkFlowOid(), "workFlowOid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getWorkFlowOtype(), "workFlowOtype");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getDisabled(), "disabled");

        try {
            TypeWorkFlowRule workFlowRule = this.typlmWorkFlowRuleService.createWorkflowRule(typeWorkFlowRule);
            if (workFlowRule != null) {
                WorkFlow workFlow = this.typlmWorkFlowService.getWorkFlowByWorkFlowId(workFlowRule.getWorkFlowOid());
                if (workFlow != null) {
                    String description = String.format("流程模板规则:%s", workFlow.getName());
                    TyplmAuditLogUtil.info(workFlowRule.getTypeoid(), workFlowRule.getTypeotype(), LogEventEnum.ADD, description);
                }
            }

            return ResponseResult.success();
        } catch (Exception var5) {
            TyplmAuditLogUtil.errorInfo(new CTyEntityBaseDO(typeWorkFlowRule.getTypeoid(), typeWorkFlowRule.getTypeotype()), LogEventEnum.ADD, "流程模板规则", var5);
            throw var5;
        }
    }

    @PostMapping({"/updateTypeWorkflowRule"})
    @ApiOperation(
            value = "修改流程模板规则",
            notes = "修改流程模板规则",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult updateTypeWorkflowRule(@RequestBody TypeWorkFlowRule typeWorkFlowRule) {
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getOid(), "oid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getTypeoid(), "typeoid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getTypeotype(), "typeotype");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getLifeCycleStageKeys(), "lifeCycleStageKeys");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getWorkFlowOid(), "workFlowOid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getWorkFlowOtype(), "workFlowOtype");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getDisabled(), "disabled");

        try {
            this.typlmWorkFlowRuleService.updateWorkflowRule(typeWorkFlowRule);
            WorkFlow workFlow = this.typlmWorkFlowService.getWorkFlowByWorkFlowId(typeWorkFlowRule.getWorkFlowOid());
            if (workFlow != null) {
                String description = String.format("更新流程模板名称为%s", workFlow.getName());
                TyplmAuditLogUtil.info(typeWorkFlowRule.getTypeoid(), typeWorkFlowRule.getTypeotype(), LogEventEnum.UPDATE_OBJECT, description);
            }

            return ResponseResult.success();
        } catch (Exception var4) {
            TyplmAuditLogUtil.errorInfo(typeWorkFlowRule.getOid(), typeWorkFlowRule.getOtype(), LogEventEnum.UPDATE_OBJECT, var4);
            throw var4;
        }
    }

    @PostMapping({"/deleteTypeWorkflowRule"})
    @ApiOperation(
            value = "删除流程模板规则",
            notes = "删除流程模板规则",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult deleteTypeWorkflowRule(@RequestBody TypeWorkFlowRule typeWorkFlowRule) {
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getOid(), "oid");
        this.typlmWorkFlowRuleService.deleteTypeWorkflowRule(typeWorkFlowRule);
        return ResponseResult.success();
    }

    @PostMapping({"/changeTypeWorkflowRuleStatus"})
    @ApiOperation(
            value = "更改流程模板规则启停用状态",
            notes = "更改流程模板规则启停用状态",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult changeTypeWorkflowRuleStatus(@RequestBody TypeWorkFlowRule typeWorkFlowRule) {
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getOid(), "oid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getTypeoid(), "typeoid");
        ArgumentUtils.checkArgumentNull(typeWorkFlowRule.getDisabled(), "disabled");

        try {
            this.typlmWorkFlowRuleService.changeWorkflowRuleStatus(typeWorkFlowRule);
            return ResponseResult.success();
        } catch (Exception var4) {
            AuditLogDO auditLogDO = new AuditLogDO();
            auditLogDO.setDescription("流程模板规则");
            TyplmAuditLogUtil.errorInfo(LogEventEnum.ENABLEORDISABLE, auditLogDO, var4);
            throw var4;
        }
    }

    @PostMapping({"/queryLifecycleByType"})
    @ApiOperation(
            value = "根据类型获取生命周期模板的阶段",
            notes = "根据类型获取流程模板规则列表",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult<List<LifekeysVo>> queryLifecycleByType(@RequestBody TypesAndLifekeysDto dto) {
        ArgumentUtils.checkArgumentNull(dto.getTypeOid(), "typeoid");
        return ResponseResult.success(this.typlmWorkFlowRuleService.queryLifecycleByType(dto));
    }

    @PostMapping({"/queryTypeWorkflowRule"})
    @ApiOperation(
            value = "根据类型获取流程模板规则列表",
            notes = "根据类型获取流程模板规则列表",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult<List<TypeWorkFlowRule>> queryWorkflowRule(@RequestBody TypesAndLifekeysDto dto) {
        ArgumentUtils.checkArgumentNull(dto.getTypeOid(), "typeoid");
        return ResponseResult.success(this.typlmWorkFlowRuleService.queryWorkflowRule(dto));
    }

    @PostMapping({"/queryWorkflowByObjList"})
    @ApiOperation(
            value = "根据对象获取共同的流程模板",
            notes = "根据对象获取共同的流程模板",
            produces = "application/json; charset=utf-8"
    )
    public ResponseResult<List<WorkFlow>> queryWorkflowByObjList(@RequestBody WorkFlowQueryDTO workFlowQuery) {
        BigInteger containerOid = workFlowQuery.getContainerOid();
        String containerOtype = workFlowQuery.getContainerOtype();
        String nameCodeLike = workFlowQuery.getNameCodeLike();
        ArgumentUtils.checkArgumentEmpty(containerOid, "containerOid");
        ArgumentUtils.checkArgumentEmpty(containerOtype, "containerOtype");
        List<WorkFlow> list=this.typlmWorkFlowRuleService.queryWorkflowByObjList(workFlowQuery.getObjList(), nameCodeLike, containerOid, containerOtype);

        List<BaseObject> objList=workFlowQuery.getObjList();
        if(objList!=null){
            //String disabled = null;
            String mapperStr = null;
            try {
//                disabled = new String(
//                        SpringUtil.getProperty("system.process.disabled").getBytes("ISO-8859-1"), "UTF-8");
                mapperStr = new String(
                        SpringUtil.getProperty("system.process.mapper").getBytes("ISO-8859-1"), "UTF-8");

            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

//            for(int a=0;a<objList.size();a++){
//                BigInteger oid = objList.get(a).getOid();
//                String oType = objList.get(a).getOtype();
//                if(disabled!=null){
//                    String []disableds=disabled.split(",");
//                    for(int i=0;i<disableds.length;i++){
//                        if(disableds[i].equals(oType)){
//                            throw  MyCollectErrorCodeEnum.vue.getException( "类型为【"+disabled+"】的已被禁止走流程");
//                        }
//                    }
//                }
//            }


            if(mapperStr!=null){
                BigInteger oid = objList.get(0).getOid();
                String oType = objList.get(0).getOtype();
                JSONObject mapperJson=JSONObject.parseObject(mapperStr);

                if("ty.inteplm.part.CTyPart".equals(oType)){
                    PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);

                    //类型 自制件 标准件 定制件 成品 辅料 样机物料采购BOM ERP不管控零部件
                    String typeName=partDetailsVO.getTypeName();

                    //INWORK正在工作，UNDERREVIEW正在审阅，DESIGN APPROVED✰设计发布，PROTOTYPE★样机发布
                    //PRODUCTION⭐️量产发布，TRIALPRODUCTION⭐️小批量发布，RELEASED⭐️已发布
                    String lifecycleStateKey=partDetailsVO.getLifecycleStateKey();
                    String view=partDetailsVO.getView();

                    log.info(JSONObject.toJSONString(mapperJson));

                    if(mapperJson.containsKey(view)==false){
                        //暂时取消弹出
                        //throw  MyCollectErrorCodeEnum.vue.getException( "该视图【"+view+"】未在properties中配置流程");
                    }
                    JSONArray viewArr=mapperJson.getJSONArray(view);


                    Map<String,WorkFlow> workFlowMap=new HashMap<>();
                    for(int i=0;i<viewArr.size();i++){
                        JSONObject viewObj=viewArr.getJSONObject(i);
                        if(lifecycleStateKey.equals(viewObj.getString("LifecycleStateKey"))){
                            for(int a=0;a<list.size();a++){
                                if(list.get(a).getName().equals(viewObj.getString("processName"))){
                                    workFlowMap.put(list.get(a).getName(),list.get(a));
                                    break;
                                }
                            }
                        }
                    }

//                    for(int a=0;a<list.size();a++){
//                        if(workFlowMap.containsKey(list.get(a).getName())==false){
//                            list.remove(a);
//                            a--;
//                        }
//                    }
                }

            }
        }


        if(list.size()==0){
            //throw  MyCollectErrorCodeEnum.vue.getException( "该零部件未在properties中配置流程");
        }
        return ResponseResult.success(list);
    }

}
